<template>
  <div id="dwv" class="dwvDiv" v-if="isShow">
    <div class="button-row">
      <mt-button class="mt-raised mt-primary" value="Scroll" v-on:click="switchTool('Scroll')">Scroll</mt-button>
      <mt-button class="mt-raised mt-primary" value="WindowLevel"
        v-on:click="switchTool('WindowLevel')">WindowLevel</mt-button>
      <mt-button class="mt-raised mt-primary" value="ZoomAndPan"
        v-on:click="switchTool('ZoomAndPan')">ZoomAndPan</mt-button>
      <!-- <mt-button class="mt-raised mt-primary" value="Sharpen" v-on:click="switchTool('Sharpen')">Sharpen</mt-button>
      <mt-button class="mt-raised mt-primary" value="Draw" v-on:click="switchTool('DicomTags')">DicomTags</mt-button> -->
    </div>
    <div class="layerContainer">
      <div class="dropBox"></div>
      <canvas class="imageLayer" ref="imageLayer">Only for HTML5 compatible browsers...</canvas>
    </div>
    <div class="legend">{{ legend }}</div>
  </div>
</template>

<script>
import dwv from "dwv";
import { useApi } from "@scmt/core-api";
import {
  useNotify
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import html2canvas from "html2canvas";
import { useUtils } from "@scmt/lib-utils";

const $api = useApi();
const $notify = useNotify();
const $utils = useUtils();
// decode query
dwv.utils.decodeQuery = dwv.utils.base.decodeQuery;
// progress
dwv.gui.displayProgress = function () { };
// window
dwv.gui.getWindowSize = dwv.gui.base.getWindowSize;
// get element
dwv.gui.getElement = dwv.gui.base.getElement;
// refresh element
dwv.gui.refreshElement = dwv.gui.base.refreshElement;

const editingObj = ref(null);

const { request, data } = useRequest({
  //根据登记Id查询dcm
  registrationDcmCrl: async (registrationId) => {
    return await $api.pacs.dcmUrl.queryDcmUrlByRegistrationId(registrationId);
  },
  //保存dcm转为png 的png 数据
  saveDcmImage: async (item) => {
    return await $api.pacs.imageData.saveDcmImage(item.list, item.registrationId).then(() => {
      $notify.success("保存影像成功");
    });
  }
});


export default {
  name: "dwv",
  data: function () {
    return {
      legend: "Powered by dwv " + dwv.getVersion(),
      dwvApp: "",
      isShow: false,
    };
  },
  props: {
    selectItemTag: Object
  },
  components: {
  },
  mounted() {
    this.initDwv();
  },
  methods: {
    /**
     * 初始化 dwvApp
     */
    initDwv() {
      // create app
      this.dwvApp = new dwv.App();
      // initialise app
      this.dwvApp.init({
        elem: this.$refs.dwvContainer,
        containerDivId: "dwv",
        fitToWindow: true,
        tools: ["Scroll", "ZoomAndPan", "WindowLevel", "Sharpen", "Darw"],
        isMobile: true,
      });
    },
    /**
     * 清除 dwvApp
     */
    clearDwv() {
      // 清理 DWV 应用
      if (this.dwvApp) {
        if (this.dwvApp.cleanup) {
          this.dwvApp.cleanup();
        }

      }
    },
    /**
     * 切换到指定的工具
     * @param toolName  工具名称
     */
    switchTool: function (toolName) {
      if (this.dwvApp) {
        let event = {
          currentTarget: {
            value: toolName
          }
        }
        // 切换到指定的工具
        this.dwvApp.onChangeTool(event);
      } else {
        console.error('DWV application is not initialized properly');
      }
    },
    Scroll: function () {
      this.switchTool("Scroll")
    },
    WindowLevel: function () {
      this.switchTool("WindowLevel")
    },
    ZoomAndPan: function () {
      this.switchTool("ZoomAndPan")
    },
    Draw: function () {
      this.switchTool("draw")
    },
    Sharpen: function () {
      this.switchTool("Sharpen")
    },
    saveImage: function () {
      html2canvas(this.$refs.imageLayer, {
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        useCORS: true, //支持图片跨域
        scale: 1, //设置放大的倍数
      }).then((canvas) => {
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        let url = canvas.toDataURL('image/png') // toDataURL: 图片格式转成 base64
        let list = [];
        let item = $api.pacs.imageData.$$createEntity({ registrationId: editingObj.value?.id ?? "" });
        item.id = $utils.uuid();
        item.imageData = url;
        list.push(item);
        request("saveDcmImage", { registrationId: editingObj.value.id, list: list });
      })
    },
  },
  beforeDestroy() {
    //清除 dwvApp
    this.clearDwv();
  },
  watch: {
    selectItemTag: {
      immediate: true, // 初始化时让handler调用一下
      // handler什么时候调用？当isHot发生改变时。
      handler(newValue, oldValue) {
        let item = newValue;
        if (item) {
          this.isShow = false;
          editingObj.value = $api.pacs.registration.$$createEntity({});
          if (item.id) {
            item.patientType = item.patientType + "";
            editingObj.value = $api.pacs.registration.$$createEntity(item);
            this.isShow = true;
            //清除 dwvApp
            this.clearDwv();
            this.initDwv();
            query("registrationDcmCrl", item.id).then((resData) => {
              let urls = data.registrationDcmCrl ?? [];
              let urlArray = [];
              if (urls && urls.length > 0) {
                urls.forEach(element => {
                  urlArray.push(element.url)
                });
                // this.dwvApp.loadURLs([
                //   "/dcmServer/bbmri-53323851.dcm",
                // ]);
                this.dwvApp.loadURLs(urlArray);

              }
              else {
                this.isShow = false;
                $notify.warning("当前登记单还没有影像");
              }

            });
          }
        }
      },
    }
  },
};

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#dwv {
  font-family: Arial, Helvetica, sans-serif;
  height: 100%;
}

.button-row {
  text-align: center;
}

.legend {
  text-align: center;
  font-size: 8pt;
}

/* Layers */
.layerContainer {
  position: relative;
  padding: 0;
  margin: auto;
  text-align: center;
  height: 100%;
}

.imageLayer {
  position: absolute;
  left: 0px;
}

/* drag&drop */
.dropBox {
  border: 5px dashed #ccc;
  margin: auto;
  text-align: center;
}

.dropBox.hover {
  border: 5px dashed #cc0;
}
</style>
